﻿/**************************************************************************************************************
 * Class name:  BasePage.cs
 * Description: ASP.NET 项目所用母页，集成常用功能
 * Author:      Ju2ender
 * Create:      2012-10-22 Monday 16:02:25
 * Update:      2012-10-26 Friday 18:34:03
 **************************************************************************************************************/

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using DearLee.Toolkit.Enums;
using DearLee.Toolkit.Globalization;

namespace DearLee.Toolkit.Web {

  /// <summary>
  /// ASP.NET 项目所用母页，集成常用功能
  /// </summary>
  public class BasePage : System.Web.UI.Page {

    #region Convert

    /// <summary>
    /// 将给定字符串减短
    /// </summary>
    /// <param name="keyId">当前记录主键</param>
    /// <param name="content">要转换的字符串</param>
    /// <param name="maxLength">最大长度</param>
    /// <returns></returns>
    public string ConvertToShort(object keyId, object content, int maxLength) {

      int intKeyId = 0;
      string str = string.Empty;

      intKeyId = Convert.ToInt32(keyId);

      if (intKeyId > 0) {
        str = content.ToString();

        if (str.Length > maxLength) {
          str = str.Substring(0, maxLength) + "...";
        }
      }

      return str;
    }

    /// <summary>
    /// 将给定字符串减短
    /// </summary>
    /// <param name="content">要转换的字符串</param>
    /// <param name="maxLength">最大长度</param>
    /// <returns></returns>
    public string ConvertToShort(string content, int maxLength) {

      string str = string.Empty;

      str = content.ToString();

      if (str.Length > maxLength) {
        str = str.Substring(0, maxLength) + "...";
      }

      return str;
    }

    /// <summary>
    /// 将给定字符串转换为百分比，类似于 23.45%
    /// </summary>
    /// <param name="keyId">当前记录主键</param>
    /// <param name="num">要转换的字符串</param>
    /// <returns></returns>
    public string ConvertToPercent(object keyId, object num) {

      int intKeyId = 0;
      string str = string.Empty;

      intKeyId = Convert.ToInt32(keyId);

      if (intKeyId > 0) {

        double db = 0;

        db = Convert.ToDouble(num) * 100;

        if (db > 100) {
          db = 100;
        }

        str = Convert.ToDouble(db).ToString("0.00") + "%";
      }

      return str;
    }

    /// <summary>
    /// 将给定字符串转换为百分比，类似于 23.45%
    /// </summary>
    /// <param name="num">要转换的字符串</param>
    /// <returns></returns>
    public string ConvertToPercent(double num) {

      string str = string.Empty;
      double db = 0;

      db = num * 100;

      if (db > 100) {
        db = 100;
      }

      str = Convert.ToDouble(db).ToString("0.00") + "%";

      return str;
    }

    /// <summary>
    /// 将给定字符串转换为保留两位有效数字的浮点型，并加上人名币符号，
    /// 类似于：￥100.00
    /// </summary>
    /// <param name="keyId">当前记录主键</param>
    /// <param name="rmb">要转换的字符串</param>
    /// <returns></returns>
    public string ConvertToRmb(object keyId, object rmb) {

      string sRmb = string.Empty;
      int iKeyId = Convert.ToInt32(keyId);

      if (iKeyId > 0) {
        sRmb = "￥" + Convert.ToDouble(rmb).ToString("0.00");
      }

      return sRmb;
    }

    /// <summary>
    /// 将给定字符串转换为保留两位有效数字的浮点型，并加上人名币符号，
    /// 类似于：￥100.00
    /// </summary>
    /// <param name="rmb">要转换的字符串</param>
    /// <returns></returns>
    public string ConvertToRmb(double rmb) {

      return "￥" + rmb.ToString("0.00");
    }

    /// <summary>
    /// 将给定字符串转换为性别
    /// </summary>
    /// <param name="keyId">当前记录主键</param>
    /// <param name="gender">要转换的字符串</param>
    /// <returns></returns>
    public string ConvertToGender(object keyId, object gender) {

      string sGender = string.Empty;
      int iKeyId = Convert.ToInt32(keyId);

      if (iKeyId > 0) {

        sGender = ((Gender)Enum.Parse(typeof(Gender), gender.ToString())).ToString();
      }

      return sGender;
    }

    /// <summary>
    /// 将给定字符串转换为性别
    /// </summary>
    /// <param name="gender">要转换的字符串</param>
    /// <returns></returns>
    public string ConvertToGender(int gender) {

      return ((Gender)Enum.Parse(typeof(Gender), gender.ToString())).ToString();
    }

    /// <summary>
    /// 绑定时间
    /// ISO 8601 标准：yyyy-MM-dd HH:mm:ss
    /// 当时间为 1900-1-1 0:00:00 时会显示为减号 -
    /// </summary>
    /// <param name="datetime">时间</param>
    /// <returns></returns>
    public string BindDateTimeForDisplay(object datetime) {

      DateTime d_datetime, check_datetime;

      d_datetime = Convert.ToDateTime(datetime);
      check_datetime = new DateTime(1900, 1, 1, 0, 0, 0);

      if (check_datetime == d_datetime) {
        return "-";
      }

      return d_datetime.ToString("yyyy-MM-dd HH:mm:ss");
    }

    /// <summary>
    /// 绑定时间
    /// ISO 8601 标准：yyyy-MM-dd HH:mm:ss
    /// 当时间为 1900-1-1 0:00:00 时会显示为空字符串
    /// </summary>
    /// <param name="datetime">时间</param>
    /// <returns></returns>
    public string BindDateTimeForSelect(object datetime) {

      DateTime d_datetime, check_datetime;

      d_datetime = Convert.ToDateTime(datetime);
      check_datetime = new DateTime(1900, 1, 1, 0, 0, 0);

      if (check_datetime == d_datetime) {
        return string.Empty;
      }

      return d_datetime.ToString("yyyy-MM-dd HH:mm:ss");
    }

    #endregion

    #region Bind Dropdownlist

    /// <summary>
    /// 绑定生肖下拉列表
    /// </summary>
    /// <param name="ddl"></param>
    public void BindDdlYearOfBirth(DropDownList ddl) {

      List<ListItem> list = null;

      list = EnumHelper.ListEnum(typeof(YearOfBirth));

      BindDdl(ddl, list);
      AddDefaultListItem(ddl);
    }

    /// <summary>
    /// 绑定星座下拉列表
    /// </summary>
    /// <param name="ddl"></param>
    public void BindDdlConstellation(DropDownList ddl) {

      List<ListItem> list = null;

      list = EnumHelper.ListEnum(typeof(Constellation));

      BindDdl(ddl, list);
      AddDefaultListItem(ddl);
    }

    /// <summary>
    /// 绑定血型下拉列表
    /// </summary>
    /// <param name="ddl"></param>
    public void BindDdlBloodType(DropDownList ddl) {

      List<ListItem> list = null;

      list = EnumHelper.ListEnum(typeof(BloodType));

      BindDdl(ddl, list);
      AddDefaultListItem(ddl);
    }

    /// <summary>
    /// 绑定是否下拉列表
    /// </summary>
    /// <param name="ddl"></param>
    public void BindDdlYesNo(DropDownList ddl) {

      List<ListItem> list = null;

      list = new List<ListItem> {
        new ListItem { Text = "是", Value = "1" },
        new ListItem { Text = "否", Value = "0" }
      };

      BindDdl(ddl, list);
      AddDefaultListItem(ddl);
    }

    /// <summary>
    /// 绑定性别下拉列表
    /// </summary>
    /// <param name="ddl"></param>
    public void BindDdlGender(DropDownList ddl) {

      List<ListItem> list = null;

      list = EnumHelper.ListEnum(typeof(Gender));

      list.Reverse();
      BindDdl(ddl, list);
      AddDefaultListItem(ddl);
    }

    /// <summary>
    /// 绑定年龄下拉菜单
    /// </summary>
    /// <param name="ddl"></param>
    /// <param name="maxAge">最大年龄</param>
    public void BindDdlAge(DropDownList ddl, int maxAge) {

      List<ListItem> list = null;

      list = new List<ListItem>();

      for (int i = 0; i <= maxAge; i++) {
        list.Add(new ListItem {
          Text = i.ToString(),
          Value = i.ToString()
        });
      }

      BindDdl(ddl, list);
      AddDefaultListItem(ddl);
    }

    /// <summary>
    /// 为 list 添加默认项
    /// </summary>
    /// <param name="list"></param>
    /// <returns></returns>
    public void AddDefaultListItem(DropDownList ddl) {
      ddl.Items.Insert(0, new ListItem { Text = "", Value = "-1" });
    }

    /// <summary>
    /// 为下拉列表绑定数据源
    /// </summary>
    /// <param name="ddl">下拉列表</param>
    /// <param name="list">数据源</param>
    public void BindDdl(DropDownList ddl, List<ListItem> list) {

      ddl.DataSource = list;
      ddl.DataTextField = "Text";
      ddl.DataValueField = "Value";
      ddl.DataBind();
    }

    /// <summary>
    /// 绑定枚举下拉列表
    /// </summary>
    /// <param name="ddl"></param>
    /// <param name="oEnum"></param>
    public void BindDdlEnum<T>(DropDownList ddl) {
      BindDdl(ddl, EnumHelper.ListEnum(typeof(T)));
    }

    #endregion

    #region Form

    /// <summary>
    /// 清空表单
    /// </summary>
    /// <param name="ctrl"></param>
    public void ResetForm(Control ctrl) {

      for (int i = 0; i < ctrl.Controls.Count; i++) {

        if (ctrl.Controls[i] is TextBox) {
          (ctrl.Controls[i] as TextBox).Text = string.Empty;
        }
        else if (ctrl.Controls[i] is HtmlInputText) {
          (ctrl.Controls[i] as HtmlInputText).Value = string.Empty;
        }
        else if (ctrl.Controls[i] is HtmlTextArea) {
          (ctrl.Controls[i] as HtmlTextArea).Value = string.Empty;
        }
        else if (ctrl.Controls[i] is DropDownList) {
          (ctrl.Controls[i] as DropDownList).SelectedIndex = 0;
        }
        else if (ctrl.Controls[i] is HtmlInputCheckBox) {
          (ctrl.Controls[i] as HtmlInputCheckBox).Checked = false;
        }
        else if (ctrl.Controls[i] is HtmlInputRadioButton) {
          (ctrl.Controls[i] as HtmlInputRadioButton).Checked = false;
        }
        else if (ctrl.Controls[i].HasControls()) {
          ResetForm(ctrl.Controls[i]);
        }
      }
    }

    #endregion

    #region File upload

    /// <summary>
    /// 上传文件
    /// </summary>
    /// <param name="inputFile">HtmlInputFile 控件 Id</param>
    /// <param name="savePath">
    /// 存储路径，最后需带上斜杠，
    /// 如：\\127.0.0.1\upload\；
    /// 或：/upload/
    /// </param>
    /// <returns>文件名</returns>
    public string FileUpload(HtmlInputFile inputFile, string savePath) {

      string fileName, // 文件名称
             extentsion, // 扩展名
             storageLocation; // 存储路径

      fileName = string.Empty;

      // 若 HtmlInputFile 控件中的文件为空，则返回
      if (inputFile.PostedFile.ContentLength == 0) {
        return fileName;
      }

      // 若指定的存储路径不存在，则创建
      if (!Directory.Exists(savePath)) {
        Directory.CreateDirectory(savePath);
      }

      extentsion = inputFile.Value.Substring(inputFile.Value.LastIndexOf('.'),
                                             inputFile.Value.Length - inputFile.Value.LastIndexOf('.'));

      fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + extentsion;
      storageLocation = savePath + fileName;
      inputFile.PostedFile.SaveAs(storageLocation);

      return fileName;
    }

    #endregion

    #region Hidden Area

    /// <summary>
    /// 根据名称获得隐藏域中的值
    /// </summary>
    /// <param name="hidden">隐藏域中的值</param>
    /// <param name="name">名称</param>
    /// <returns></returns>
    public string GetHiddenValue(string hiddenValue, string name) {

      int index_start, index_end = 0;

      index_start = hiddenValue.IndexOf(name + "=");

      if (index_start == -1) {
        return string.Empty;
      }

      index_start = index_start + name.Length + 1;
      index_end = hiddenValue.IndexOf("&", index_start);

      if (index_end == -1) {
        index_end = hiddenValue.Length;
      }

      return hiddenValue.Substring(index_start, index_end - index_start);
    }

    #endregion
  }
}
